package com.cn.main.framework;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * user : chenyuncong
 * create_time : 2022/8/22
 */
@Component
public class SpringBean  implements ApplicationContextAware {
//    private static final Logger log = LoggerFactory.getLogger(SpringBean.class);


    private  static ApplicationContext applicationContext;

    private SpringBean(){}

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBean.applicationContext = applicationContext;
    }

    public static <T> T getSpringBean(Class<T> clazz){
        return SpringBean.applicationContext.getBean(clazz);
    }
    @SuppressWarnings("unchecked")
    public static <T> T getSpringBean(String beanName){
        return (T) SpringBean.applicationContext.getBean(beanName);
    }

    public static void inject(Object object){
        if(object == null)
            return;
        Class clazz = object.getClass();
        while (clazz != Object.class) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                Autowired annotation = field.getAnnotation(Autowired.class);
                if (annotation != null) {
//                    field.getType()
//                    Reflector.setFieldValue(object,field,SpringBean.getSpringBean(field.getType()));
                }

                Resource resource = field.getAnnotation(Resource.class);
                if (resource != null) {
//                    Reflector.setFieldValue(object,field,SpringBean.getSpringBean(field.getName()));
                }
            }
            clazz = clazz.getSuperclass();
        }
    }
}
